package cn.kgc;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wangyue
 * @version 1.0
 */
public class Demo5 {
    private static ExecutorService executors = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        m3();
    }

    private static void m3() {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            return "任务1的返回结果";
        }, executors);
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            return "任务2的返回结果";
        }, executors);
        //任务3等待任务1和任务2执行完成以后在执行,在任务3中可以获得任务1和任务2的返回值,任务3中有返回值
        CompletableFuture<String> future3 = future1.thenCombine(future2, (s1, s2) -> {
            System.out.println("任务3执行了,任务1的返回值是:" + s1 + ",任务2的返回值是:" + s2);
            return "任务3的返回结果";
        });
        String s = null;
        try {
            s = future3.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(s);
        //关闭线程池
        executors.shutdown();
    }

    private static void m2() {
        //任务1
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            return "任务1的返回结果";
        }, executors);
        //任务2
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            return "任务2的返回结果";
        }, executors);
        //任务3等待前面的任务1和任务2都执行完以后在执行,任务3中获得任务1和任务2的返回值 任务3中没有返回值
        future1.thenAcceptBothAsync(future2, (s1, s2) -> {
            System.out.println("任务3执行了,任务1的返回值是:" + s1 + ",任务2的返回值是:" + s2);
        },executors);
        //关闭线程池
        executors.shutdown();
    }

    private static void m1() {
        //任务1
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            return "任务1的返回结果";
        }, executors);
        //任务2
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            return "任务2的返回结果";
        }, executors);
        //任务3等待前面的任务1和任务2都执行完以后在执行,任务3中不能过获得任务1和任务2的返回值 任务3中没有返回值
        future1.runAfterBothAsync(future2, () -> {
            System.out.println("任务3执行了");
        }, executors);
        //关闭线程池
        executors.shutdown();
    }
}
